<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>在线音乐服务器</title>
    <link rel="shortcut icon" href="#"/>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/jquery-3.1.1.min.js"></script>
    <style>
        td, th { text-align: center; color: crimson; }
        h1, .l1 { color: crimson; }
        body { background: url(images/bg1.png); background-repeat: repeat-x; background-size: 100%; }
        audio { height: 40px; }
        .player-controls { margin-top: 15px; }
    </style>
    <script>
        $(document).ready(function () {
            load();
            $(document).ajaxError(function (event, xhr) {
                if (xhr.status === 401) {
                    alert("您尚未登录，请先登录！");
                    window.location.href = "/login.html";
                }
            });

            $("form").submit(function (event) {
                event.preventDefault(); // 阻止默认提交行为
                $("#submit1").click(); // 触发查询按钮的点击事件
            });
        });

        function load(musicName = "") {
            $.ajax({
                url: "/music/findMusic",
                type: "get",
                data: { musicName: musicName },
                dataType: "json",
                success: function (obj) {
                    var data = obj.data;
                    var s = '';
                    data.forEach(music => {
                        s += `<tr>
                                <th><input id="${music.id}" type="checkbox"></th>
                                <td>${music.title}</td>
                                <td>${music.type}</td>
                                <td>${music.singer}</td>
                                <td><button class="btn btn-primary" onclick="playerSong('${music.url}')">播放</button></td>
                                <td>
                                    <button class="btn btn-danger" onclick="deleteInfo(${music.id})">删除</button>
                                    <button class="btn btn-success" onclick="loveInfo(${music.id})">喜欢</button>
                                </td>
                              </tr>`;
                    });
                    $("#info").html(s);
                }
            });
        }

        // 停止当前播放的音频
        function stopCurrentSong() {
            var audio = document.getElementById('musicPlayer');
            audio.pause();
            audio.currentTime = 0;
        }

        // 播放歌曲
        function playerSong(url) {
            stopCurrentSong(); // 停止当前播放的音频

            var encodedUrl = encodeURI(url);
            console.log('编码前：' + url + '；编码后：' + encodedUrl);
            $.ajax({
                type: "get",
                url: encodedUrl,
                success: function (resp) {
                    if (resp.status === 0) {
                        var musicData = atob(resp.data);
                        var uint8Array = new Uint8Array(musicData.length);
                        for (var i = 0; i < musicData.length; i++) {
                            uint8Array[i] = musicData.charCodeAt(i);
                        }
                        var blob = new Blob([uint8Array], { type: 'audio/mpeg' });
                        var musicUrl = URL.createObjectURL(blob);
                        var audio = document.getElementById('musicPlayer');
                        audio.src = musicUrl;
                        audio.play();
                    } else {
                        alert("播放失败，请联系管理员！");
                    }
                },
                error: function () {
                    alert("音乐加载失败！");
                }
            });
        }

        function deleteInfo(id) {
            $.post("/music/delete", { id: id }, function (data) {
                if (data.status === 0) {
                    alert("删除成功");
                    load();
                } else {
                    alert("删除失败");
                }
            }, "json");
        }

        function loveInfo(id) {
            $.post("/loveMusic/addMyLove", { musicId: id }, function (data) {
                alert(data.status === 0 ? "加入喜欢的列表成功" : "加入失败或已存在！");
                load();
            }, "json");
        }

        $(function () {
            $("#submit1").click(function () {
                var name = $("#exampleInputName2").val();
                load(name);
            });

            $("#delete").click(function () {
                var ids = $("input:checkbox:checked").map(function () {
                    return $(this).attr("id");
                }).get();
                if (ids.length === 0) return alert("请选择要删除的音乐");
                $.post("/music/deleteSelect", { ids: ids }, function (data) {
                    alert(data.status === 0 ? "批量删除成功" : "删除失败");
                    load();
                }, "json");
            });
        });
    </script>
</head>

<body>
<h1 style="text-align: center">在线音乐服务器</h1>
<div style="float: left;">
    <form class="form-inline">
        <div class="form-group">
            <label for="exampleInputName2" class="l1">歌曲名</label>
            <input name="name" type="text" class="form-control" id="exampleInputName2">
        </div>
        <button id="submit1" type="button" class="btn btn-primary">查询</button>
    </form>
</div>
<div style="float: right; margin-bottom: 15px" class="player-controls">
    <audio controls id="musicPlayer">
        Your browser does not support the audio element.
    </audio>
    <a class="btn btn-primary" href="loveMusic.html">喜欢列表</a>
    <a class="btn btn-primary" href="upload.html">添加歌曲</a>
    <a id="delete" class="btn btn-primary">删除选中</a>
</div>
<table border="1" class="table table-bordered table-hover">
    <tr class="success">
        <th>选择</th>
        <th>歌名</th>
        <th>格式</th>
        <th>歌手</th>
        <th>歌曲</th>
        <th>操作</th>
    </tr>
    <tbody id="info"></tbody>
</table>
</body>

</html>
